package com.yege.lab.book;

import com.alibaba.fastjson.JSON;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;


/**
 * @author yege
 */
@Service
public class BookService {
    private final static Log log = LogFactory.getLog(BookService.class);
    private final static String KEY_BOOK="book_info";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void addBook(BookDto book){
        String bookStr=JSON.toJSONString(book);
        stringRedisTemplate.opsForList().leftPush(KEY_BOOK,bookStr);
        log.info("upload book info successful!");
    }

    public List<BookDto> queryBook(){
        List<BookDto> bookList=new ArrayList<>();
        long size=stringRedisTemplate.opsForList().size(KEY_BOOK);
        List<String> bookStrList=stringRedisTemplate.opsForList().range(KEY_BOOK,0,size);
        bookStrList.forEach(book->{ bookList.add(JSON.parseObject(book,BookDto.class));});
        return bookList;
    }
}
